import java.util.HashMap;

public class BuildTree {

    int[] preorder;
    int[] inorder;
    HashMap<Integer, Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.inorder = inorder;
        this.preorder = preorder;
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return process(0, preorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode process(int preL, int preR, int midL, int midR) {
        if (preL > preR || midL > midR) return null;
        TreeNode node = new TreeNode(preorder[preL]);
        int index = map.get(preorder[preL]);
        node.left = process(preL + 1, index - midL + preL, midL, index + 1);
        node.right = process(index - midL + preL + 1, preR, index + 1, midR);
        return node;
    }
}
